import socket
import os
import sys
from playsound import playsound

addr = '192.168.163.12'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((addr, 8000))  # IP,端口
sock.listen(5)  # 支持排队等待的是5个

command = False


while True:
    conn, addr = sock.accept()  # 等待客户端来连接，如果没有监测端来连接，则一直卡在这里
    # conn是连接管道，addr是发起连接的监测端地址
    print('收到检测器连接……')

    conn.sendall('控制系统连接成功'.encode('utf-8'))
    while True:

        client_data = conn.recv(1024)  # 等待监测端发来数据
        if not client_data:
            break
        data = client_data.decode('utf-8')
        if data == 'Sound':
            playsound('1.mp3')
        elif data == 'shutdown':
            os.system("shutdown -s -t 0")
        elif data == 'restart':
            os.system("shutdown -r -t 0")
        elif data == 'command':
            command = True
        elif data == 'qcommand':
            command = False
        else:
            if command:
                os.system(data)
            else:
                print(data)
    print('关闭连接')
    conn.close()  # 关闭双方连接

sock.close()  # 服务端中止后续连接
